#include "UDPServer.hpp"

using namespace server;

void handleMessage(int sockfd, string client_ip, uint16_t client_port, string message)
{
    // 可以自行定义对message的处理方法而不关系message是如何来的，做到网络通信与业务逻辑的解耦
    string response;
    response += message;

    // 返回给客户端
    struct sockaddr_in client;
    bzero(&client, sizeof client);
    client.sin_family = AF_INET;
    client.sin_port = htons(client_port);
    client.sin_addr.s_addr = inet_addr(client_ip.c_str());

    sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&client, sizeof(client));
}

// ./UDPServer port
int main(int argc, char **argv)
{
    if (argc != 2)
    {
        UDPServer::usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = static_cast<uint16_t>(atoi(argv[1]));

    unique_ptr<UDPServer> udp_server(new UDPServer(handleMessage, port));

    udp_server->initServer();
    udp_server->start();

    return 0;
} //@end main